import rcontrolutil
import Tkinter
import itertools

def add_items(tkmenu, listargs):
	if not tkmenu:
		raise rcontrolutil.RException('Must call add_menu before adding items.')
	if len(listargs)==1 and (isinstance(listargs, list) or isinstance(listargs, tuple)):
		listargs = listargs[0]
		
	if len(listargs)%2!=0:
		raise rcontrolutil.RException("Provide menuitems in the format ('a',fnA,'b',fnB,'__',None,'c',fnC). (The list you provided had an odd # of elements)")
	for label, function in _pairwise(listargs):
		if label and label.replace('_','')=='':
			#it's a separator
			if function!=None: raise rcontrolutil.RException("'Seperator' menuitems, like '___', must have a function of None.")
			tkmenu.add_separator()
		else:		
			opts={}
			spl = label.split('|')
			if len(spl)>2: rcontrolutil.RException("Invalid menuitem syntax, too many |")
			if len(spl)==2:
				opts['accelerator'] = spl[1]
				label = spl[0]
			label, underline = rcontrolutil.stringToUnderlinePosition(label)
			if underline!=-1: opts['underline']=underline
			if function: opts['command']=function
			tkmenu.add_command(label=label, **opts)
	return None
	

def add_check_item(tkmenu, strText, fnCommand=None, bChecked=True):	
	var = Tkinter.IntVar()
	if bChecked: var.set(1)
	else: var.set(0)
	
	opts={}
	if fnCommand: opts['command']=fnCommand
	label, underline = rcontrolutil.stringToUnderlinePosition(strText)
	if underline!=-1: opts['underline']=underline

	tkmenu.add_checkbutton(label=label, variable=var, onvalue=1, offvalue=0, **opts)
	return RMenuCheckItem(var)
		

class RMenuCheckItem():
	_variable = None
	def __init__(self, tkvar):
		self._variable = tkvar
	def get_checked(self):
		if self._variable.get(): return True
		else: return False
	def set_checked(self, val):
		if val: self._variable.set(1)
		else: self._variable.set(0)

#~ class RMenuItem(rcontrol.RControl):
	#~ _type = 
	#~ accelerator, text, command, checked (true or false), that is, if a variable.

def _pairwise(iterable):
	"s -> (s0,s1), (s1,s2), (s2, s3), ..."
	assert len(iterable)%2==0
	for y in range(0, len(iterable), 2):
		yield (iterable[y], iterable[y+1])
	
if __name__=='__main__':
	for a,b in _pairwise([1,2,3,4,5,6]):
		print a,b
		
	